<?php
namespace app\admin\job;

use think\facade\Db;
use think\queue\Job;
use think\facade\Log;

/**
 * @Title: app\task\job$Import
 * @Package package_name
 * @Description: todo(测试订单消费者)
 * @author Zl <1079313358@qq.com>
 * @date 2020年06月17日
 */
class ImportUser{
    /**
     * @Title: fire
     * @Description: todo(fire方法是消息队列默认调用的方法)
     * @param Job $job
     * @param array $data
     * @author Zl <1079313358@qq.com>
     * @date 2021年06月17日
     * @throws
     */
    public function fire(Job $job, $data)
    {
        //有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->excel_import($data);

        if ($isJobDone) {
            //如果任务执行成功，记得删除任务
            $job->delete();
        }else{
            //通过这个方法可以检查这个任务已经重试了几次了
            if ($job->attempts() > 3){
                Log::error('试了3次了');

                $logData = [
                    'content' => json_encode($data['rows'], JSON_UNESCAPED_UNICODE),
                ];
                Db::name('excel_log')->insert($logData);


                $job->delete();

                //也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * @Title: checkDatabaseToSeeIfJobNeedToBeDone
     * @Description: todo(有些消息在到达消费者时,可能已经不再需要执行了)
     * @param array $data
     * @return boolean
     * @author Zl <1079313358@qq.com>
     * @date 2021年06月17日
     * @throws
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    /**
     * @Title: excel_import
     * @Description: todo(数据处理)
     * @param array $data
     * @author Zl <1079313358@qq.com>
     * @date 2020年06月17日
     * @throws
     */
    public function excel_import($data)
    {
        try {
            // 对excel表格数据做处理并插入到数据库中
            $insert = [
                "name"           => isset($data['rows'][1]) ? $data['rows'][1] : '',
                "source"         => isset($data['rows'][2]) ? $data['rows'][2] : '',
                "level"          => isset($data['rows'][3]) ? $data['rows'][3] : '',
                "area"           => isset($data['rows'][4]) ? $data['rows'][4] : '',
                "fotype"         => isset($data['rows'][5]) ? $data['rows'][5] : '',
                "remark"         => isset($data['rows'][6]) ? $data['rows'][6] : '',
                "contacter"      => isset($data['rows'][7]) ? $data['rows'][7] : '',
                "telephone"      => isset($data['rows'][8]) ? $data['rows'][8] : '',
                "city_level"     => isset($data['rows'][9]) ? $data['rows'][9] : '',
                "detail_address" => isset($data['rows'][13]) ? $data['rows'][13] : '',
                "create_user_id" => $data['create_user_id'],
                "create_time"    => time(),
            ];

            // $leads_owner_id = isset($data['rows'][29]) && $data['rows'][29] ? Db::name('admin_user')->where(['realname'=> $data['rows'][29]])->value('id') : 0;
            $leads_touch_id = isset($data['rows'][29]) && $data['rows'][29] ? Db::name('admin_user')->where(['realname'=> $data['rows'][29]])->value('id') : 0;
            // $insert['owner_user_id'] = $leads_owner_id ?? 0; // 负责人
            $insert['owner_user_id'] = 0;
            $insert['supply_user_id'] = 1;
            $insert['touch_user_id'] = $leads_touch_id; // 触达人
            $insert['touch_time'] = $leads_touch_id == 0 ? 0 : time(); 

            $insert['province_id'] = 0;
            $insert['city_id']     = 0;
            $insert['county_id']   = 0;

            if (isset($data['rows'][10]) && $data['rows'][10]) {
                $province_id = Db::name('shop_region')
                    ->where('name', 'like', '%'.$data['rows'][10].'%')
                    ->value('id');
                $insert['province_id'] = $province_id ?? 0;
            }

            if (isset($data['rows'][11]) && $data['rows'][11]) {
                $city_id = Db::name('shop_region')
                    ->where('name', 'like', '%'.$data['rows'][11].'%')
                    ->value('id');
                $insert['city_id'] = $city_id ?? 0;
            }

            if (isset($data['rows'][12]) && $data['rows'][12]) {
                $county_id = Db::name('shop_region')
                    ->where('name', 'like', '%'.$data['rows'][12].'%')
                    ->value('id');
                $insert['county_id'] = $county_id ?? 0;
            }

            $leadsData = $insert; // 需要插入线索表的数据
            
            $insert['shop_alias']    = isset($data['rows'][14]) ? $data['rows'][14] : ''; // 店铺别名
            $insert['atv']           = isset($data['rows'][15]) ? $data['rows'][15] : '';
            $insert['wom']           = isset($data['rows'][16]) ? $data['rows'][16] : '';
            $insert['store_area']    = isset($data['rows'][17]) ? $data['rows'][17] : '';
            // 根据用户名查询负责人id 和触达人id 客户负责人id 和 转化人id
            // $customer_owner_id = isset($data['rows'][31]) && $data['rows'][31] ? Db::name('admin_user')->where(['realname'=> $data['rows'][31]])->value('id') : 0;
            $customer_trans_id = isset($data['rows'][30]) && $data['rows'][30] ? Db::name('admin_user')->where(['realname'=> $data['rows'][30]])->value('id') : 0;
            // $insert['owner_user_id'] = $customer_owner_id ?? 0; // 负责人
            $insert['owner_user_id'] = 0;
            $insert['trans_user_id'] = $customer_trans_id == 0 ? $leads_touch_id : $customer_trans_id; // 转化人
            $insert['address']       = $data['rows'][10].' '.$data['rows'][11].' '.$data['rows'][12];
            $customerData = $insert; // 需要插入客户表中的数据
            unset($customerData['touch_user_id'],$customerData['supply_user_id'],$customerData['touch_time']);
            
            $customerData['king_no'] = isset($data['rows'][19]) ? $data['rows'][19] : '';
            $houseCode =  isset($data['rows'][20]) ? Db::name('shop_warehouse')->where(['name'=> $data['rows'][20]])->value('kingdee_code','') : ''; // 发货仓库
            $customerData['house_code'] = $houseCode;
            // 绑定信息添加
            $bindData = [
                'contacter' => isset($data['rows'][27]) ? $data['rows'][27] : '', // 收货人
                'telephone' => isset($data['rows'][28]) ? $data['rows'][28] : '', // 收货联系电话
                'address'   => isset($data['rows'][26]) ? $data['rows'][26] : '', // 详细地址
                'king_no'   => isset($data['rows'][19]) ? $data['rows'][19] : '', // 金蝶编码
                'house_code'=> $houseCode, // 发货仓库
                "create_user_id" => $data['create_user_id'],
                "create_time" => time(),
            ];

            if (isset($data['rows'][23]) && $data['rows'][23]) {
                $province = Db::name('shop_region')
                    ->where('name', 'like', '%'.$data['rows'][23].'%')
                    ->value('id');
                $bindData['province'] = $province ?? 0;
            }

            if (isset($data['rows'][24]) && $data['rows'][24]) {
                $city = Db::name('shop_region')
                    ->where('name', 'like', '%'.$data['rows'][24].'%')
                    ->value('id');
                $bindData['city'] = $city ?? 0;
            }

            if (isset($data['rows'][25]) && $data['rows'][25]) {
                $county = Db::name('shop_region')
                    ->where('name', 'like', '%'.$data['rows'][25].'%')
                    ->value('id');

                $bindData['district'] = $county ?? 0;
            }


            if ( $data['rows'][0] == 3 ) { // 线索已成功转化为客户 已交易
                // 先添加客户数据 再添加绑定数据 最后添加线索到数据表
                $customerData['district_id'] = $customerData['county_id'];
                unset($customerData['county_id']);
                $customerData['status'] = 2;  // 1待处理 2 已成交 3 未成交
                $customerData['deal_time']   = time();

                $customerId = Db::name('crm_customer')->insertGetId($customerData);

                $bindData['customer_id'] = $customerId;
                Db::name('crm_customer_bind')->insert($bindData);

                $leadsData['customer_id']  = $customerId;
                $leadsData['is_transform'] = 1;
                $leadsData['trans_time'] = time();
                Db::name('crm_leads')->insert($leadsData);

                // 添加联系人1数据
                $contactData = [
                    'customer_id' => $customerId,
                    'name'        => isset($data['rows'][7]) ? $data['rows'][7] : '',
                    'mobile'      => isset($data['rows'][8]) ? $data['rows'][8] : '',
                    'create_time' => time(),
                ];
                Db::name('crm_contacts')->insert($contactData);

                
                // 添加联系人2数据
                if( !empty($data['rows'][31]) ){
                    $contactData = [
                    'customer_id' => $customerId,
                    'name'        => isset($data['rows'][7]) ? $data['rows'][7] : '',
                    'mobile'      => isset($data['rows'][31]) ? $data['rows'][31] : '',
                    'create_time' => time(),
                    ];
                    Db::name('crm_contacts')->insert($contactData);
                }
                
            }

            if ( $data['rows'][0] == 2 ) { // 线索已成功转化为客户
                // 先添加客户数据 再添加绑定数据 最后添加线索到数据表
                $customerData['district_id'] = $customerData['county_id'];
                unset($customerData['county_id']);
                $customerData['status'] = 1; // 1待处理 2 已成交 3 未成交
                $customerId = Db::name('crm_customer')->insertGetId($customerData);

                $leadsData['customer_id']  = $customerId;
                $leadsData['is_transform'] = 1;
                $leadsData['trans_time'] = time();
                Db::name('crm_leads')->insert($leadsData);
            }

            if ( $data['rows'][0] == 1 ) { // 线索状态
                // 先添加客户数据 再添加绑定数据 最后添加线索到数据表
                $leadsData['is_transform'] = 0;
                Db::name('crm_leads')->insert($leadsData);
            }
        } catch (\Exception $e) {
            Log::info('error message:'.$e->getMessage());
            return false;
        }
//        Log::info(date('Y-m-d H:i:s').' - data：'.json_encode($data));
        return true;
    }
}
